<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use DiDom\Document;
use App\Model\FangzhouListIask;
class FangzhouDetailIask extends Model

{   public static function get_iask_detail($keyword,$flag_id,$key_id,$url){
   
      $from = "爱问";
      $FangzhouDetail = FangzhouDetailIask::where('flag_id',$flag_id)->where('from',$from)->first();
      if(!$FangzhouDetail||1){
          $document = new Document($url, true);
          $title_html =  $document->find("h1");
          $title = "";
          if(isset($title_html[0])&&$title_html[0]->text()){
              $title = $title_html[0]->text();
          }else{
            $title_html =  $document->find(".qs_cont");
            if(isset($title_html[0])&&$title_html[0]->text()){
              $title = $title_html[0]->text();
            }
          }
          if($title){
            $good_answer = $document->find(".wb2_good_answer"); 

            if($good_answer){
              if($good_answer[0]->find(".answer_all")){
                $good_answer = $good_answer[0]->find(".answer_all pre")[0]->text();
              }else if($good_answer[0]->find(".answer_lit")){

                $good_answer = $good_answer[0]->find(".answer_lit pre")[0]->text();
              }else{
                $good_answer = "";
              }
            }else{
                $good_answer = "";              
            }
            
            $other_answer_html =$document->find(".more_answer_dd"); 
            $other_answer = [];   
            if($other_answer_html){
              foreach ($other_answer_html as $key => $value) {
                if($value->find(".answer_all")){
                  $text = $value->find(".answer_all pre")[0]->text();
                  $match="/\[.*\]/";           
                  $other_answer[] = preg_replace($match, "", $text );
                }else if($value->find(".answer_lit")){
                  $text = $value->find(".answer_lit pre")[0]->text();
                  $match="/\[.*\]/";           
                  $other_answer[] = preg_replace($match, "", $text );
                }
              }
            }

            $FangzhouDetail = new FangzhouDetailIask;
            $FangzhouDetail->flag_id = $flag_id;
            $FangzhouDetail->key_id = $key_id;
            $FangzhouDetail->from = $from;
            $FangzhouDetail->keyword = $keyword;       
            $FangzhouDetail->save();
            $FangzhouListBaidu = new FangzhouListIask;
            $FangzhouListBaidu->detail_id = $FangzhouDetail->id;
            $FangzhouListBaidu->title = $title;
            $FangzhouListBaidu->answer = $good_answer;
            $FangzhouListBaidu->other_answer = json_encode($other_answer);
            $FangzhouListBaidu->save();

          }
      }
    }
   
}
